// import TableFilterMixin from '@/mixins/TableFilterMixin'
import { Component } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import { Button } from 'ant-design-vue'
import { RedoOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import type { FormItemDto } from '@/components/low-code/types'
import {
    getSaleList,
    getInsuranceCompanyList,
    getLongInsuranceCount,
    getLongInsuranceCaseList,
    getPeriodInsuranceMaterials,
    exportPeriodInsuranceCaseList,
    getMaterialInsureCompany
} from '@/api/insurance/period/index'
import type {
    LongInsuranceCaseListDto,
    InsuraceSaleDto,
    InsuraceeCompanyListDto,
    InsuranceCountDto,
    LongInsuranceCaseDto,
    ReportCaseResultDto,
    PeriodInsuranceMaterialsDto,
    InsuranceMaterialsFileDto
} from '@/api/insurance/period/types'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import {
    type VxeGridPropTypes,
    type VxeTableDataRow,
    type VxeColumnSlotTypes,
} from 'vxe-table'
import TableDetail from '../components/TableDetail'
import SetInfoPop from '../components/SetInfoPop'
import SetMaterialPop from '../components/SetMaterialPop'
import AddClaimsPop from '../components/AddClaimsPop'
import { ref,computed } from 'vue'
import { downloadFile, getCompanyListByName } from '@/utils/util'
import userStore from '@/stores/user'
export interface FilterDto {
    [key: string]: FormItemDto
}
@Component
export class LongInsuranceView extends TableRender {
    insureCompanyList = [] as string[]
    showAddClaims = false
    insuranceMaterialInfo = {} as LongInsuranceCaseListDto<ReportCaseResultDto>
    showSetInfo = false
    insuranceBasicInfo = {} as LongInsuranceCaseListDto<ReportCaseResultDto>
    showSetMaterialInfo = false
    isDelState = true
    noFilterPadding = true
    longInsuranceCount = {} as InsuranceCountDto
    previewList = [] as PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]
    insureData = [
        { title: '案件总数', key:'totalReportCaseCount'  },
        { title: '待理赔', key:'totalClaimsPendingCount'  },
        { title: '已确认金额', key:'totalNotarizePriceCount'  },
        { title: '已结案', key:'totalSettleLawsuitCount'  },
        { title: '撤案/驳回', key:'totalRejectCount'  },
        { title: '已理赔金额', key:'totalFinalMoney'  },
        { title: '预估金额', key:'totalEstimateMoney'  },
    ] as { title: string, key: string }[]
    insuranceStateObj = {
        0: {label: '待处理',value: 0,color:'text-yellow'},
        1: {label: '处理中',value: 1,color:'text-blue-light-100'},
        2: {label: '已结案', value: 2,color:'text-green'},
        3: {label: '已驳回',value: 3,color:'text-red'},
        4: {label: '已撤销',value: 4,color:'text-black-300'},
        5: {label: '已确认金额',value: 5,color:'text-blue'},
        6: {label: '保险垫付',value: 6,color:'text-blue'}
    } as { [key: number]: { label: string, value: number, color: string } }
    onDeleteProgress() {
        this.reloadPage()
    }
    tableColumnConfigOld = () => [
        {
            type: 'expand',
            title: '详情',
            width: '100',
            slots: {
                content: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams<LongInsuranceCaseListDto<ReportCaseResultDto>>)  => {
                    return (
                        <div class="flex"><TableDetail onDeleteChange={this.onDeleteProgress} type='long' item={ row }  /></div>
                    )
                }
            }
        },
        {
            field: 'id',
            title: 'id',
            width: '100',

        },
        {
            title: '状态',
            width: '150',
            slots: {
                // insuranceStateObj
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                    return (
                        <div class={this.insuranceStateObj[row.reportStatus].color}>
                            { this.insuranceStateObj[row.reportStatus].label }
                        </div>
                    )
                }
            }

        },
        {
            field: 'companyName',
            title: '公司名',
        },
        {
            field: 'outDangerUserName',
            title: '出险人姓名',
        },
        
        {
            field: 'serveCompanyName',
            title: '被派遣单位',
        },
        {
            field: 'insurCompanyName',
            title: '承保公司',
        },
        {
            title: '可用工种',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                    return (
                        <div class="flex">
                            {row.occupationName} ({ row.occupationLevel }类)
                        </div>
                    )
                }
            }
        },
        {
            title: '金额',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                    return (
                        <div class=" ">
                            <div>预估金额：<span style="color: #FF7642;">{ row.estimateMoney === null ? '--' : row.estimateMoney }</span></div>
                            <div>最终金额：<span style="color: #9497B1;">{ row.finalMoney === null ? '--' : row.finalMoney }</span></div>
                        </div>
                    )
                }
            }
        },
        {
            field: 'salesName',
            title: '所属业务员',
        },
        {
            field: 'createTime',
            title: '录入时间',
        },
        {
            title: '操作',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams<LongInsuranceCaseListDto<ReportCaseResultDto>>) => {
                    return (
                        <div class="flex items-center">
                            {/* insureCompanyList */}
                            <div class="text-blue-light-100 mr-2 cursor-pointer" onClick={() => this.onOpenSetInfo(row)}>设置</div>
                            {
                                this.canShowAdd(row.insurCompany) && this.hasPermission('period-insur:report-case-bccl:query')
                                    ? <div class="text-blue-light-100 cursor-pointer" onClick={() => this.onOpenSetMaterialInfo(row)}>材料</div>
                                    : ''
                            }
                        </div>
                    )
                }
            }
        },
        
    ] as TableRenderColumnTypes<ReportCaseResultDto>

    filterConfig(){
        return {
            companyId: {
                name: '公司名称',
                element: 'select',
                placeholder: '请输入后选择',
                optionsType: 'company'
            },
            serveCompanyId: {
                name: '派遣单位',
                element: 'select',
                placeholder: '请输入后选择',
                optionsType: 'serveCompany'
            },
            outDangerUserName: {
                name: '出险人名称',
                element: 'input',
            },
            outDangerPhone: {
                name: '出险人手机号',
                element: 'input',
            },
            reportStatus: {
                name: '保险状态',
                element: 'select',
                options: [
                    {label: '待受理',value: 0, },
                    {label: '处理中', value: 1,},
                    {label: '已结案',value: 2,},
                    {label: '已驳回',value: 3,},
                    {label: '已撤销', value: 4, },
                    {label: '已确认金额',value: 5, },
                    { label: '保险垫付', value: 6,},
                ]
            },
            salesId: {
                name: '所属商务',
                element: 'select',
                placeholder: '请输入后选择',
                remote:true,
                options:[],
                params: {
                    method: async (event: string) => {
                        if (event) { 
                            const res = await getSaleList({ isSelectSale: 1,salesName:event })
                            this.filters.serveCompanyId.options = res.map((item:InsuraceSaleDto) => ({
                                label: item.saleName,
                                value: item.saleId
                            }))
                        }
                    }
                },
            },
            outDangerIdCardNo: {
                name: '出险人身份证',
                element: 'input',
            },
            reportPhone:{ 
                name: '报案人手机号',
                element: 'input',
            },
            insurCompany: {
                name: '保司名称',
                element: 'select',
                value:'',
                options:[],
                params: {
                    method: async (event: string) => {
                        if (event) { 
                            console.log(event, '获取保司列表')
                        }
                    }
                },
            },
            uploadStatus: {
                name: '材料状态',
                element: 'select',
                options: [{ label: '全部', value: '' }, {label:'已上传','value':'1'},{label:'未上传','value':'0'}]
            },
            dateRange: {
                name: '出险日期',
                element: 'datetime',
                type: 'daterange',
                value: '',
                params: {
                    valueFormat: 'YYYY-MM-DD'
                }
            },
            search: {
                name: '搜索',
                element: 'button',
                span: 1,
                class: 'relative',
                callback: {
                    click: ()=> { console.log(this.getFilters(),'huoqu1jguo1')}
                }
            },
            clear: {
                name: (
                    <div class="ml-8 text-black-light-200 flex items-center">
                        <div class="mr-4">
                            <RedoOutlined style="fontSize:16px" />
                        </div>
						
                        清空条件
                    </div>
                ),
                element: 'button',
                params: {
                    text: true
                },
                span: 2,
                callback: {
                    click: () => {
                        console.log('点击了')
                    }
                }
            }
        } as FilterDto
    }
    renderRightBtns() {
        return (
            <div class="flex flex-row-reverse mt-4">
                <Button icon={ <DownloadOutlined /> } type="text" onClick={ this.onOpenAddClaims }>
                    新增报案
                </Button>
                <Button icon={ <DownloadOutlined />} type="text" onClick={this.onExportPeriodInsuranceCaseList}>
                    导出
                </Button>
            </div>
        )
    }
    

    insureDataDom() { 
        return (
            <div class="flex items-center justify-between gap-6">
                {
                    this.insureData.map((item: {title:string,key:string}) => { 
                        return (
                            <div class="flex-1 flex flex-col items-center bg-black-400 pt-14 pb-8">
                                <div class="font-semibold text-black-light-100">{ this.longInsuranceCount[item.key] }</div>
                                <div class="text-xs">{ item.title }</div>
                            </div>
                        )
                    })
                }
                

            </div>
        )
    }
   
    // 打开新增报案弹窗
    onOpenAddClaims() { 
        this.showAddClaims = true
    }
	
    canShowAdd(companyCode: string) {
        return this.insureCompanyList.some((i: string) => i === companyCode)
    } 
    hasPermission(prem: string) { 
        const user =  userStore()
        return user.permissions.some((i: string) => i === prem)
    }

    // 导出报案列表
    async onExportPeriodInsuranceCaseList() { 
        const data = this.getFilters() as LongInsuranceCaseDto
        console.log(data, 'datadata')
        if (data.dateRange) {
            data.outDangerStartDate = data.dateRange[0] || ''
            data.outDangerEndDate = data.dateRange[1] || ''
            data.dateRange = undefined 
        }
        const url = await exportPeriodInsuranceCaseList(data)
        downloadFile(url)
        console.log(url, 'urlurl')
    }
    // 打开设置弹窗并且存储row数据
    onOpenSetInfo(data:LongInsuranceCaseListDto<ReportCaseResultDto>) { 
        this.insuranceBasicInfo = data
        this.showSetInfo = true
    }
    // 打开设置材料弹窗
    async onOpenSetMaterialInfo(event: LongInsuranceCaseListDto<ReportCaseResultDto>) {
        // 获取理赔材料列表
        this.insuranceMaterialInfo = event 
        await this.initPeriodInsuranceMaterials()
        this.showSetMaterialInfo = true
    }
    // 获取理赔材料列表
    async initPeriodInsuranceMaterials() {
        const result = await getPeriodInsuranceMaterials({
            reportCaseId: Number(this.insuranceMaterialInfo.id),
            insureCompany: this.insuranceMaterialInfo.insurCompany,
        })
        this.previewList = result
        console.log(result, 'resultresultresult')
        return
    }
    
    // 获取保司列表
    async initInsuranceCompanyList() { 
        const result = await getInsuranceCompanyList()
        this.filters.insurCompany.options = result.map((item: InsuraceeCompanyListDto) => { 
            return {
                label: item.dictLabel,
                value: item.dictValue
            }
        })
    }
    // 获取长期保险统计
    async initLongInsuranceCount() {
        const result = await getLongInsuranceCount()
        this.longInsuranceCount = result
    }

    
    render() {
        return (
            <div class="flex flex-col h-full overflow-hidden">
                <div>
                    {this.renderFilter()}
                </div>
				
                {this.insureDataDom()}
                { this.renderRightBtns() }
                {this.renderTable()}
                {this.renderPager()}
                {
                    <SetInfoPop
                        v-model:show={this.showSetInfo}
                        basicInfo={this.insuranceBasicInfo}
                        onRefresh={this.reloadPage}
                        type='period'
                    />
                }
                {
                    <SetMaterialPop
                        v-model:show={ this.showSetMaterialInfo }
                        previewList={this.previewList}
                        basicInfo={this.insuranceMaterialInfo}
                        type="period"
                        onChange={this.initPeriodInsuranceMaterials}
                    />
                }
                {
                    <AddClaimsPop
                        v-model:show={this.showAddClaims}
                        onChange={this.reloadPage}
                    />
                }
            </div>
        )
    }
    async created() {
        this.insureCompanyList = await getMaterialInsureCompany()
        console.log(this.insureCompanyList, 'resultdhsal1')
        this.initLongInsuranceCount()
        this.initInsuranceCompanyList()
    }
    onLoadData(page: number, size: number, filters: LongInsuranceCaseDto) {
        console.log(filters, 'filtersfilters')
        if (filters.dateRange) {
            filters.outDangerStartDate = filters.dateRange[0] || ''
            filters.outDangerEndDate = filters.dateRange[1] || ''
            filters.dateRange = undefined 
        }
        return getLongInsuranceCaseList({
            pageNum: page,
            pageSize: size,
            ...filters
        })
    }
}

export default toNative<{}, {}>(LongInsuranceView)